<template>
  <div class="admin-venues">
    <el-header class="header">
      <div class="header-content">
        <div class="logo">
          <h2>🏟️ 场地管理系统</h2>
        </div>
        <div class="nav">
          <el-button @click="$router.push('/admin/dashboard')" type="primary">仪表板</el-button>
          <el-button @click="$router.push('/admin/activities')">活动管理</el-button>
          <el-button @click="$router.push('/admin/coaches')">教练管理</el-button>
          <el-button @click="logout" type="danger">退出登录</el-button>
        </div>
      </div>
    </el-header>
    
    <el-main class="main-content">
      <el-card class="venues-card">
        <template #header>
          <div class="card-header">
            <span>🏟️ 场地管理</span>
            <el-button type="primary" @click="openCreateDialog">
              <el-icon><Plus /></el-icon>
              新增场地
            </el-button>
          </div>
        </template>

        <!-- 搜索栏 -->
        <el-row :gutter="20" style="margin-bottom: 20px">
          <el-col :span="6">
            <el-input
              v-model="searchName"
              placeholder="搜索场地名称"
              clearable
              @input="handleSearch"
            >
              <template #append>
                <el-button :icon="Search"></el-button>
              </template>
            </el-input>
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="searchAddress"
              placeholder="搜索场地地址"
              clearable
              @input="handleSearch"
            >
              <template #append>
                <el-button :icon="Location"></el-button>
              </template>
            </el-input>
          </el-col>
          <el-col :span="6">
            <el-select
              v-model="statusFilter"
              placeholder="选择状态"
              clearable
              @change="handleSearch"
            >
              <el-option label="启用" :value="1" />
              <el-option label="停用" :value="0" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="handleSearch" :icon="Search">
              搜索
            </el-button>
            <el-button @click="resetSearch" :icon="Refresh">
              重置
            </el-button>
          </el-col>
        </el-row>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
          <el-skeleton :rows="5" animated />
        </div>

        <!-- 场地列表 -->
        <el-table v-else :data="venuesList" border style="width: 100%">
          <el-table-column prop="id" label="ID" width="80"></el-table-column>
          <el-table-column prop="name" label="场地名称" width="200"></el-table-column>
          <el-table-column prop="address" label="地址" width="250"></el-table-column>
          <el-table-column prop="description" label="描述" show-overflow-tooltip></el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag v-if="scope.row.status === 1" type="success">启用</el-tag>
              <el-tag v-else type="info">停用</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="250">
            <template #default="scope">
              <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
              <el-button size="small" @click="toggleStatus(scope.row)">
                {{ scope.row.status === 1 ? '停用' : '启用' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          v-if="total > 0"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="total"
          style="margin-top: 20px; text-align: center"
        />

        <!-- 空状态 -->
        <div v-if="!loading && venuesList.length === 0" class="empty-state">
          <el-empty description="暂无场地数据" />
        </div>
      </el-card>
    </el-main>

    <!-- 新增/编辑场地对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑场地' : '新增场地'"
      width="50%"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="场地名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入场地名称"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入场地地址"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入场地描述"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="启用" :value="1"></el-option>
            <el-option label="停用" :value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Location, Refresh } from '@element-plus/icons-vue'
import { venueApi } from '@/api'

const router = useRouter()
const venuesList = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchName = ref('')
const searchAddress = ref('')
const statusFilter = ref('')
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref()

// 表单数据
const form = ref({
  id: null,
  name: '',
  address: '',
  capacity: 50,
  description: '',
  status: 1
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入场地名称', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入场地地址', trigger: 'blur' }
  ],
  capacity: [
    { required: true, message: '请输入容量', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 获取场地列表
const fetchVenues = async () => {
  loading.value = true
  try {
    const params = {
      current: currentPage.value,
      size: pageSize.value
    }
    
    // 添加搜索条件
    if (searchName.value) {
      params.name = searchName.value
    }
    if (searchAddress.value) {
      params.address = searchAddress.value
    }
    if (statusFilter.value !== '') {
      params.status = statusFilter.value
    }
    
    const response = await venueApi.getVenueList(params)
    venuesList.value = response.data.venues || []
    total.value = response.data.total || 0
    console.log('场地数据加载成功:', response)
  } catch (error) {
    console.error('获取场地列表失败:', error)
    ElMessage.error('获取场地列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchVenues()
}

// 重置搜索
const resetSearch = () => {
  searchName.value = ''
  searchAddress.value = ''
  statusFilter.value = ''
  currentPage.value = 1
  fetchVenues()
}

// 分页处理
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchVenues()
}

// 打开创建对话框
const openCreateDialog = () => {
  isEdit.value = false
  form.value = {
    id: null,
    name: '',
    address: '',
    capacity: 50,
    description: '',
    status: 1
  }
  dialogVisible.value = true
}

// 编辑场地
const handleEdit = (row) => {
  isEdit.value = true
  form.value = { ...row }
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()
    
    if (isEdit.value) {
      // 更新场地
      await venueApi.updateVenue(form.value)
      ElMessage.success('更新成功')
    } else {
      // 创建场地
      await venueApi.createVenue(form.value)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    fetchVenues()
  } catch (error) {
    console.error('提交场地信息失败:', error)
    ElMessage.error('提交失败')
  }
}

// 删除场地
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个场地吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await venueApi.deleteVenue(row.id)
    ElMessage.success('删除成功')
    fetchVenues()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除场地失败:', error)
      ElMessage.error('删除场地失败')
    }
  }
}

// 切换场地状态
const toggleStatus = async (row) => {
  try {
    await venueApi.toggleVenueStatus(row.id)
    ElMessage.success('状态更新成功')
    fetchVenues()
  } catch (error) {
    console.error('更新场地状态失败:', error)
    ElMessage.error('更新场地状态失败')
  }
}

// 退出登录
const logout = () => {
  localStorage.removeItem('token')
  localStorage.removeItem('userInfo')
  ElMessage.success('退出登录成功')
  router.push('/login')
}

onMounted(() => {
  console.log('场地管理页面已加载')
  fetchVenues()
})
</script>

<style scoped>
.admin-venues {
  min-height: 100vh;
  background: #f5f7fa;
}

.header {
  background: white;
  border-bottom: 1px solid #e0e0e0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.logo h2 {
  margin: 0;
  color: #333;
}

.nav .el-button {
  margin-left: 10px;
}

.main-content {
  padding: 20px;
}

.venues-card {
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.loading-container {
  padding: 40px;
}

.empty-state {
  padding: 60px 20px;
  text-align: center;
}

.dialog-footer {
  text-align: right;
}
</style>

